package sw6.visualschedule.entities;

import java.io.File;
import java.io.IOException;

import sw6.lib.Settings;
import sw6.visualschedule.R;
import tools.SingletonMediaPlayer;
import tools.ThumbnailHelper;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "steps")
public class Step implements OnClickListener, IVisualScheduleElement{

	public static final String ACTIVITY_ID_FIELD = "activity_id";
	
    public static final String AUDIO_FIELD = "audio";
    public static final String COUNTDOWN_FIELD = "countdown";
    public static final String IMAGE_FIELD = "image";
    public static final String MEDIA_TYPE_FIELD = "mediatype";
    public static final String ORDER_FIELD = "order";
    public static final String TITLE_FIELD = "title";
    private static final String LOG_NAME = "Step";
    
    @DatabaseField(columnName = ACTIVITY_ID_FIELD, foreign = true)
    private transient ScheduleActivity mActivity;
    
    @DatabaseField(columnName = AUDIO_FIELD)
    private transient String mAudio;
    
    @DatabaseField(generatedId = true)
    private transient Integer mId;
    
    @DatabaseField(columnName = IMAGE_FIELD)
    private transient String mImage;
    
    @DatabaseField(columnName = ORDER_FIELD, canBeNull = false)
    private transient Integer mOrder;
    
    @DatabaseField(columnName = TITLE_FIELD, canBeNull = false)
    private transient String mTitle;
    
    /**
     * Constructs a step and associated it with an activity.
     * Adds the step as the last step in the activity.
     * 
     * @param act the activity to add the step to.
     * @param title the title of the step.
     */
    public Step(final ScheduleActivity act, final String title) {
        mActivity = act;
        mTitle = title;
        
        if (mOrder == null) {
            final ForeignCollection<Step> oldSteps = mActivity.getSteps();
            if (oldSteps.isEmpty()) {
                mOrder = 0;
            } else {
                mOrder = mActivity.getSteps().size();
            }
        }
    }
    
    Step() {
        // all persisted classes must define a no-arg constructor with at least package visibility
    }
    
    public ScheduleActivity getActivity() {
        return mActivity;
    }
    
    public String getAudio() {
        return mAudio;
    }
    
    public Integer getId() {
        return mId;
    }
    
    public String getImage() {
        return mImage;
    }
    
    /**
     * Returns the image bitmap associated with the step.
     * If not available, a default note image will be returned.
     * 
     * @param ctx the application context.
     * @return an image bitmap.
     */
    public Bitmap getImageBitmap(final Context ctx) {
        Bitmap bitmap = null;
        
        if (mImage != null) {
            final File imageFile = new File(mImage);
            if (imageFile.exists()) {
                bitmap = BitmapFactory.decodeFile(mImage);
            }
        }

        if (bitmap == null) {
            bitmap = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.default_image);
        }
        
        return bitmap;
    }
    
    /**
     * Returns the image bitmap associated with the step, scaled to a specific max width and height.
     * If not available, a default note image will be returned.
     * 
     * @param ctx the application context.
     * @param maxWidth the maximum width the image can have.
     * @param maxHeight the maximum height the image can have.
     * @return an image bitmap.
     */
    public Bitmap getImageBitmapThumbnail(final Context ctx, final int maxWidth, final int maxHeight) {
        Bitmap bitmap = ThumbnailHelper.getImageBitmapThumbnail(mImage, maxWidth, maxHeight);
        
        if (bitmap == null) {
            bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.default_image), maxWidth, maxHeight, true);
        }
        
        return bitmap;
    }
    
    public Integer getOrder() {
        return mOrder;
    }
    
    public String getTitle() {
        return mTitle;
    }
    
    @Override
	public void onClick(View v) {
		if (mAudio != null) {
			if (Settings.getUserProfile(v.getContext()).canHear() && !"".equals(mAudio)) {
	            try {
	            	final MediaPlayer mMediaPlayer = SingletonMediaPlayer.getMediaPlayer();
	                mMediaPlayer.setDataSource(mAudio);
	                mMediaPlayer.prepare();
	                mMediaPlayer.start();
	            } catch (IllegalArgumentException e) {
	                Log.e(LOG_NAME, e.getMessage());
	            } catch (IllegalStateException e) {
	                Log.e(LOG_NAME, e.getMessage());
	            } catch (IOException e) {
	                Log.e(LOG_NAME, e.getMessage());
	            }
	        }
		}
	}
    
    public void setAudio(final String audio) {
        mAudio = audio;
    }
    
    public void setImage(final String image) {
        mImage = image;
    }
    
    public void setOrder(final Integer order) {
        mOrder = order;
    }

	public void setTitle(final String title) {
        mTitle = title;
    }
}
